package com.fitsoftwareprocess.mobilemap.bus;

import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;

import com.fitsoftwareprocess.mobimap.dto.Coordinate;
import com.fitsoftwareprocess.mobimap.dto.MapInfoEx;
import com.fitsoftwareprocess.mobimap.dto.MyCoordinate;
import com.fitsoftwareprocess.mobimap.dto.Size;

import GOOGLE.GoogleMapProviderEx;
import android.R.bool;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.widget.ImageView;

public class Map {
	private MyWebClient _MyWebClient;
	private String _Url;

	public Map(String NameSpace, String Url) {
		_MyWebClient = new MyWebClient(NameSpace);
		this._Url = Url;
	}

	 public String GetMap(Coordinate mapCenter, Coordinate homeAddress,
	            int width, int height, int zoom, int type, List<Coordinate> direction)//, double moveDx, double moveDy)
	        {
	            double DEFAULT_LONG = 106.682568;
	            double DEFAULT_LAT = 10.762795;
	            int TILE_SIZE = 256;
	            int MAX_WIDTH = TILE_SIZE * 2;
	            int MAX_HEIGHT = TILE_SIZE * 2;
	            //int DEFAULT_WIDTH = width;
	            //int DEFAULT_HEIGHT = height;
	            //int DEFAULT_ZOOM = 15;
	            int DEFAULT_TYPE = 0;
	            int screenWidth = width;
	            int screenHeight = height;
	            MapInfoEx map = new MapInfoEx();
	            map.set_zoom(zoom);
	            Size a = new Size(screenWidth, screenHeight);
	            map.set_size(a);
	            map.MapType = DEFAULT_TYPE;
	            map.CoordinateCenter = new Coordinate(mapCenter._latitude, mapCenter._longitude);

	            //move
	            //double distance = 0.00008 * Math.Pow(2, 20 - map.Zoom);
	            //if (moveDx > 0)
	            //    map.CoordinateCenter.Longitude += distance;
	            //else if (moveDx < 0)
	            //    map.CoordinateCenter.Longitude -= distance;
	            //if (moveDy > 0)
	            //    map.CoordinateCenter.Latitude += distance;
	            //else if (moveDy < 0)
	            //    map.CoordinateCenter.Latitude -= distance;

	            map.MapSource = type;//local
	            map.GlobalToMap();
	            Point k = new Point(map.MapCenter.x / TILE_SIZE, map.MapCenter.y / TILE_SIZE);
	             map.set_tile(k);
	          // String _mapStore  = pathCombine(AppDomain.CurrentDomain.BaseDirectory, "MapData");
	           String _mapStore  = pathCombine(CurrentDomain.BaseDirectory, "MapData");
	             map.set_mapStore(_mapStore);
	             ImageView resultImage;
	            if (map.MapSource == 0)
	            {
	                GoogleMapProviderEx g = new GoogleMapProviderEx();
	                resultImage = g.GetMapImage(map);
	            }
	       /*     else
	            {
	                LocalMapProviderEx g = new LocalMapProviderEx();
	                resultImage = g.GetMapImage(map);
	            }
*/
	            //Draw marker
	            Point addrPoint = new Point();
	            addrPoint = LocateConvert.ToPoint(new Coordinate(homeAddress._latitude, homeAddress._longitude), map.get_zoom());
	            int flagX = addrPoint.x - (map.MapCenter.x - resultImage.getWidth() / 2);
	            int flagY = addrPoint.y - (map.MapCenter.x - resultImage.getHeight() / 2);
	            DrawFlag(resultImage, "Image/markerGreen.png", flagX, flagY);

	            //Draw direction
	            if (direction.get(0)._latitude != -1 && direction.get(0)._longitude != -1)
	            {
	                List<Point> lstPoint = ToListScreenPoint(direction, map.MapCenter, resultImage.getWidth(), resultImage.getHeight(), map.get_zoom());
	                resultImage = DrawDirection(resultImage, map.MapCenter, lstPoint);

	                //strRespond = "street";
	                int startX = lstPoint[0].X;
	                int startY = lstPoint[0].Y;
	                DrawFlag(resultImage, @"Image/markerGreen.png", startX, startY);
	                int endX = lstPoint[lstPoint.Count - 1].X;
	                int endY = lstPoint[lstPoint.Count - 1].Y;
	                DrawFlag(resultImage, @"Image/markerRed.png", endX, endY);
	            }

	            byte[] data = imageToByteArray(resultImage);
	            string ret = Convert.ToBase64String(data);
	            return ret;
	        }

	        //Chuyen sang toa do tren man hinh
	        public List<Point> ToListScreenPoint(List<Coordinate> lst, Point mapCenter, int scrWidth, int scrHeight, int mapZoom)
	        {
	            int left = mapCenter.X - scrWidth / 2;
	            int top = mapCenter.Y - scrHeight / 2;

	            List<Point> lstPoint = new List<Point>();
	            Point p;
	            for (int i = 0; i < lst.Count; i++)
	            {
	                p = LocateConvert.ToPoint(lst[i], mapZoom);
	                lstPoint.Add(new Point(p.X - left, p.Y - top));
	            }
	            return lstPoint;
	        }

	        //Ve duong di giua 2 diem tren ban do
	        public System.Drawing.Image DrawDirection(System.Drawing.Image image, Point center, List<Point> lstPoint)
	        {
	            //System.Drawing.Image imgResult = image;

	            Graphics g = Graphics.FromImage(image);
	            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
	            Pen pen = new Pen(Color.Blue, 3);
	            Font drawFont = new Font("Arial", 12);
	            SolidBrush drawBrush = new SolidBrush(Color.Black);


	            Point startNode = lstPoint[0];
	            Point endNode = lstPoint[lstPoint.Count - 1];

	            for (int i = 0; i < lstPoint.Count - 1; i++)
	            {
	                g.DrawLine(pen, lstPoint[i], lstPoint[i + 1]);
	            }

	            return image;
	        }

	        public bool DrawFlag(ImageView resultImage, String string, int x, int y)
	        {

	           // Images flag = Images.FromFile(AppDomain.CurrentDomain.BaseDirectory + string);
	        	 Images flag = Images.FromFile(AppDomain.CurrentDomain.BaseDirectory + string);
	            int left = x - flag.Width / 2;
	            int top = y - flag.Height;

	            if (left < -flag.Width || left > resultImage.Width || top < -flag.Height || top > resultImage.Height)
	                return false;

	            Gallery g = GatheringByteChannel.FromImage(resultImage);
	            g.DrawImage(flag, left, top, 22, 34);

	            return true;
	        }
	
	
	
	/*public Bitmap getMap(Coordinate mapCenter, Coordinate homeAddress,
			int width, int height, int zoom, int type, ArrayList<Coordinate> direction) {
		String methodName = "GetMap";
		SoapObject req = _MyWebClient.GetSoapObject(methodName);

		SoapObject homeCoordinate = new SoapObject(_MyWebClient.getNameSpace(),
				methodName);
		homeCoordinate.addProperty("Longitude",
				Double.toString(homeAddress.get_longitude()));
		homeCoordinate.addProperty("Latitude",
				Double.toString(homeAddress.get_latitude()));
		PropertyInfo homeCoordiantePropInfo = new PropertyInfo();
		homeCoordiantePropInfo.setName("homeAddress");
		homeCoordiantePropInfo.setValue(homeCoordinate);
		req.addProperty(homeCoordiantePropInfo);

		SoapObject mapCenterCoordinate = new SoapObject(
				_MyWebClient.getNameSpace(), methodName);
		mapCenterCoordinate.addProperty("Longitude",
				Double.toString(mapCenter.get_longitude()));
		mapCenterCoordinate.addProperty("Latitude",
				Double.toString(mapCenter.get_latitude()));
		PropertyInfo mapCenterCoordPropInfo = new PropertyInfo();
		mapCenterCoordPropInfo.setName("mapCenter");
		mapCenterCoordPropInfo.setValue(mapCenterCoordinate);
		req.addProperty(mapCenterCoordPropInfo);

		req.addProperty("width", Integer.toString(width));
		req.addProperty("height", Integer.toString(height));
		req.addProperty("zoom", Integer.toString(zoom));
		req.addProperty("type", Integer.toString(type));
		
		SoapObject directionSoapObject = _MyWebClient.GetSoapObject(methodName);
		for(int i=0; i<direction.size(); i++){
			SoapObject coordinate = _MyWebClient.GetSoapObject(methodName);
			coordinate.addProperty("Longitude",
					Double.toString(direction.get(i).get_longitude()));
			coordinate.addProperty("Latitude",
					Double.toString(direction.get(i).get_latitude()));
			PropertyInfo coordinateProp = new PropertyInfo();
			coordinateProp.setName("Coordinate");
			coordinateProp.setValue(coordinate);
			directionSoapObject.addProperty(coordinateProp);
		}
		PropertyInfo directionProp = new PropertyInfo();
		directionProp.setName("direction");
		directionProp.setValue(directionSoapObject);
		req.addProperty(directionProp);
		

		SoapSerializationEnvelope envelope = _MyWebClient.GetEnvelope(req);
		envelope.implicitTypes = true;
		SoapPrimitive soapResult = _MyWebClient.MakeCall(_Url, envelope,
				_MyWebClient.getNameSpace(), methodName);
		String imageDataString = soapResult.toString();
		byte[] imageData = Base64.decode(imageDataString, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
	}
	*/
}
